package com.example.bookmanagement.service;

import com.example.bookmanagement.entity.Book;
import com.example.bookmanagement.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    // 获取所有图书
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    // 根据ID获取图书
    public Optional<Book> getBookById(Long id) {
        return bookRepository.findById(id);
    }

    // 保存图书
    public Book saveBook(Book book) {
        return bookRepository.save(book);
    }

    // 更新图书
    public Book updateBook(Long id, Book bookDetails) {
        Optional<Book> optionalBook = bookRepository.findById(id);
        if (optionalBook.isPresent()) {
            Book book = optionalBook.get();
            book.setTitle(bookDetails.getTitle());
            book.setAuthor(bookDetails.getAuthor());
            book.setIsbn(bookDetails.getIsbn());
            book.setPublicationYear(bookDetails.getPublicationYear());
            book.setPublisher(bookDetails.getPublisher());
            return bookRepository.save(book);
        }
        return null;
    }

    // 删除图书
    public boolean deleteBook(Long id) {
        if (bookRepository.existsById(id)) {
            bookRepository.deleteById(id);
            return true;
        }
        return false;
    }

    // 根据书名搜索
    public List<Book> searchByTitle(String title) {
        return bookRepository.findByTitleContainingIgnoreCase(title);
    }

    // 根据作者搜索
    public List<Book> searchByAuthor(String author) {
        return bookRepository.findByAuthorContainingIgnoreCase(author);
    }

    // 根据关键词搜索（书名或作者）
    public List<Book> searchByKeyword(String keyword) {
        return bookRepository.searchByTitleOrAuthor(keyword);
    }

    // 根据出版社搜索
    public List<Book> searchByPublisher(String publisher) {
        return bookRepository.findByPublisherContainingIgnoreCase(publisher);
    }

    // 检查ISBN是否存在
    public boolean isIsbnExists(String isbn) {
        return bookRepository.existsByIsbn(isbn);
    }

    // 检查ISBN是否存在（排除当前图书）
    public boolean isIsbnExists(String isbn, Long excludeId) {
        return bookRepository.existsByIsbnAndIdNot(isbn, excludeId);
    }

    // 获取图书总数
    public long getBookCount() {
        return bookRepository.count();
    }
}